﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Polly;
using System.Collections.Concurrent;
using System.Xml.Linq;
using XinLife.Core.Helper;

namespace XinLife.Common.SignalR
{
    [Microsoft.AspNetCore.Authorization.Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme + ",UserAuthent")]
    public class ChatHub : Hub<IChatClient>
    {
        public static ConcurrentDictionary<string, string> Connections = new ConcurrentDictionary<string, string>();

        //连接
        public override async Task OnConnectedAsync()
        {
            var user = AspNetUser.User.cId;

            var connectionIds = Connections.Where(t => t.Key != this.Context.ConnectionId && t.Value == user).Select(t => t.Key).ToList();
            await Clients.Clients(connectionIds).SignOut("您的账号已在其它地方登陆,是否重新登陆!!!");

            Connections.AddOrUpdate(this.Context.ConnectionId, user, (key, oldValue) => user);
            await SetOnlineNumber();
            await base.OnConnectedAsync();
        }
        //断开
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            string userid = AspNetUser.User.cId;
            var old = Connections[Context.ConnectionId];
            Connections.TryRemove(Context.ConnectionId, out old);
            await SetOnlineNumber();
            await base.OnDisconnectedAsync(exception);
        }

        //强制另一个账号退出
        public async Task ForceSignOut()
        {
            var connectionIds = Connections.Where(t => t.Key != this.Context.ConnectionId && t.Value == AspNetUser.User.cId).Select(t => t.Key).ToList();
            await Clients.Clients(connectionIds).ForceSignOut();
        }
        /// <summary>
        /// 设置在线人数
        /// </summary>
        private async Task SetOnlineNumber()
        {
            await Clients.All.SetOnlineNumber(Connections.Count());
        }


        // connection.invoke("SendMessage", "在座的都是渣渣")
        public async Task SendMessage(string msg)
        {
            await Clients.Others.SendMessage(msg);
        }

    }
}
